<?php
require_once 'pages/TMSFrontPage.inc';

abstract class TMSFrontListPage extends TMSFrontPage {
	
	protected $_int_page_size_;
	
	protected $_sort_by_ = array();
	
	protected $totalPageCount = 0;
	
	private $_page_;
	
	public function Handle(THttpRequest $request){
		if (isset($request->pn))
			$this->_page_ = $request->pn;
		parent::Handle($request);
	}
	
	public function __set($nm,$value){
		switch ($nm){
			case 'SortBy':{
				if (!is_array($value)){
					$temp = TConvertions::ConvertToArray($value,array(';','='),array(false,true));
					$value = array();
					foreach ($temp as $key=>$val){
						if ($val && !is_numeric($val))
							if (defined('TSortingType::'.$val))
								$val = constant('TSortingType::'.$val);  
							else if (defined('TSortingType::SORT_'.mb_strtoupper($val)))
								$val = constant('TSortingType::SORT_'.mb_strtoupper($val));
							else $val = null;
						else $val = null; 
						$value[] = new TSortingOption($key,$val);
					}
				}
				$this->_sort_by_ = $value;
			}break;
			default:parent::__set($nm,$value);break;
		}
	}
	
	public function __get($nm){
		switch ($nm){
			case 'CurrentListPage':return $this->_page_;break;
			case 'PageCount':return ceil($this->totalPageCount/$this->_int_page_size_);break;
			default:return parent::__get($nm);break;
		}
	}
	
	protected function getSorting(){
		return $this->_sort_by_;
	}
	
	protected function getFetchOptions(){
		$lo = new TListOptions(array(), $this->getSorting());
		if ($this->_int_page_size_){
			$lo->Offset = $this->_page_?($this->_page_ - 1)*$this->_int_page_size_:0;  
			$lo->Count = $this->_int_page_size_;
		}
		return $lo;
	}
	
	public function ListPageUrl($page){
		return $this->Url(null,null,array('pn'=>$page));
	}
	
	protected function processUrlParameters(array $parameters){
		if ($this->_page_ && !isset($parameters['pn']))
			$parameters['pn'] = $this->_page_;
		return $parameters;
	}	
	
	public abstract function Pages();
}